<template>
	<xn-form-container
		title="月累计达成金额报表"
		width="80%"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<div id="achievementAmountChart"></div>
	</xn-form-container>
</template>

<script setup>
	import { Line } from '@antv/g2plot'

	const visible = ref(false)
	const emit = defineEmits({ successful: null })

	const seriesKey = 'series'
	const valueKey = 'value'

	// 打开抽屉
	const onOpen = (record) => {
		console.log('record', record)

		visible.value = true
		setTimeout(() => {
			const data = convertData(record.repaymentDetail, record.repayTarget)
			const line = new Line('achievementAmountChart', {
				data,
				xField: 'date',
				yField: 'amount',
				seriesField: 'category',
				xAxis: {
					type: 'time'
				},
				yAxis: {
					label: {
						// 数值格式化为千分位
						formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`)
					}
				}
			})
			line.render()
		}, 100)
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	const processData = (data, yFields, meta) => {
		const result = []
		data.forEach((d) => {
			yFields.forEach((yField) => {
				const name = meta?.[yField]?.alias || yField
				result.push({ ...d, [seriesKey]: name, [valueKey]: d[yField] })
			})
		})
		return result
	}

	const convertData = (data, repayTarget) => {
		const dataObj = JSON.parse(data)
		const dataMap = new Map(Object.entries(dataObj))
		let arr = []
		for (const [key, value] of dataMap.entries()) {
			arr.push({
				date: key,
				amount: Math.round(Number(repayTarget.replace(/[^\d.-]/g, '')) / 31),
				category: '日均目标100%（元）'
			})
			arr.push({
				date: key,
				amount: Math.round((Number(repayTarget.replace(/[^\d.-]/g, '')) / 31) * 0.8),
				category: '日均目标80%（元）'
			})
			arr.push({ date: key, amount: value, category: '日回款（元）' })
		}
		// return Array.from(dataMap, ([date, value]) => ({
		// 	date: date,
		// 	targetAmount: Number(repayTarget.replace(/[^\d.-]/g, '')),
		// 	achievementAmount: value
		// }));
		return arr
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
